package cn.crm.web.controller.open;

import cn.crm.common.annotation.Anonymous;
import cn.crm.common.annotation.Log;
import cn.crm.common.core.controller.BaseController;
import cn.crm.common.core.domain.AjaxResult;
import cn.crm.common.core.domain.entity.SysUser;
import cn.crm.common.core.page.TableDataInfo;
import cn.crm.common.enums.BusinessType;
import cn.crm.common.utils.file.FileUtils;
import cn.crm.common.utils.poi.ExcelUtil;
import cn.crm.system.domain.pojo.dto.PricePdfDto;
import cn.crm.system.domain.pojo.dto.QuotedPriceDto;
import cn.crm.system.domain.pojo.dto.QuotedPricebuildDto;
import cn.crm.system.domain.pojo.dto.SeriesDto;
import cn.crm.system.domain.pojo.entity.MinioPojo;
import cn.crm.system.domain.pojo.entity.Specification;
import cn.crm.system.domain.pojo.vo.*;
import cn.crm.system.service.*;
import cn.crm.system.service.impl.BusinessServiceImpl;
import io.minio.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/openseries")
@Api(tags = "业务模块表头模块")
public class OpenSeriesController extends BaseController {

    @Autowired
    private ISeriesService seriesService;

    @Autowired
    private ICaseService caseService;
    @Autowired
    private ISpecificationService specificationService;
    @Autowired
    private IProdectService prodectService;
    @Autowired
    private IOpemSeroesService opemSeroesService;

    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioPojo minioPojo;
    @Autowired
    private BusinessServiceImpl businessService;
    @Autowired
    private ISysUserService userService;


    public OpenSeriesController() {
        log.debug("创建控制器对象：seriesController");
    }



    @Anonymous
    @GetMapping("/openlist")
    @ApiOperation("查询公开表头资料")
    public TableDataInfo Getserieslist() {
        log.debug("开始处理查询公开客户资料的接口");
        List<SeriesVo> seriesVos = seriesService.SelectSeries();
        return getDataTable(seriesVos);
    }

    @Anonymous
    @GetMapping("/banner")
    @ApiOperation("查询轮播图")
    public TableDataInfo Getbannerlist() {
        log.debug("开始处理查询公开客户资料的接口");
        List<SeriesVo> seriesVos = seriesService.Selectbanner();
        return getDataTable(seriesVos);
    }

    @Anonymous
    @GetMapping("/selectspecification")
    @ApiOperation("查询出前4笔的规格用作好物推荐")
    public TableDataInfo Getbannerlistspecification() {
        log.debug("开始处理查询公开客户资料的接口");
        List<ProdectVo> prodectVos = prodectService.selectprodectFour();
        return getDataTable(prodectVos);
    }
    @Anonymous
    @GetMapping("/selectspecifications")
    @ApiOperation("查询出前4笔的规格用作质美物好推荐")
    public TableDataInfo Getbannerlistspecifications() {
        log.debug("开始处理查询公开客户资料的接口");

        return getDataTable(null);
    }



    @Anonymous
    @GetMapping("/all")
    @ApiOperation("查询全部上品")
    public TableDataInfo GetbannerlistAll() {
        log.debug("开始处理查询公开客户资料的接口");
        List<SeriesAndadll> selectall = seriesService.selectall();
        return getDataTable(selectall);
    }

    @Anonymous
    @GetMapping("/selectUser")
    @ApiOperation("查询用户及其联系人手机")
    public AjaxResult GetUserspecifications() {
        log.debug("开始处理查询公开联系人及其手机");
        List<SysUser> sysUsers = userService.selectUserListAll();
        return success(sysUsers);
    }

    @Anonymous
    @GetMapping("/classify/{id}")
    @ApiOperation("通过id查询分类产品")
    public AjaxResult getInfo(@PathVariable Long id){
        log.debug("开始通过id查询分类接口");
        SeriesAndadll selectall = seriesService.selectallById(id);
        return  success(selectall);
    }


    @Anonymous
    @GetMapping("/all/{id}")
    @ApiOperation("通过商品id查询分类产品详情")
    public AjaxResult getInfoById(@PathVariable Long id){
        log.debug("开始通过商品id查询分类接口");
        ProdectVo selectallById = prodectService.selectProdectAllById(id);
        return  success(selectallById);
    }

    @Anonymous
    @GetMapping("/case")
    @ApiOperation("查询出所有的项目名称已经所带的联系人等")
    public TableDataInfo getInfoBycase(){

        log.debug("开始处理查询客户已经联系人以及案件资料的接口");
        List<BusinessVo> businessVo = businessService.selectbusinessListAndcast();
        return  getDataTable(businessVo);
    }

    @Anonymous
    @PostMapping( "/addoffer")
    @ApiOperation("将报价单添加到数据库")
    public AjaxResult addoffer( @RequestBody  QuotedPriceDto payload){
        log.debug("将报价单添加到数据库");
        Long aLong = opemSeroesService.insertquotedPrice(payload);
        if (aLong == null || aLong == 0 ||aLong.equals("")){
            return AjaxResult.error("添加失败");
        }
        return  success(aLong);

    }


    @Anonymous
    @PutMapping( "/updateoffer")
    @ApiOperation("将报价单修改到数据库")
    public AjaxResult updateoffer( @RequestBody  QuotedPriceDto payload){
        log.debug("将报价单添加到数据库");
        int aLong = opemSeroesService.updatequotedPrice(payload);

        return  success(aLong);

    }


    @Anonymous
    @GetMapping( "/addoffer/{id}")
    @ApiOperation("查询出打印的内容")
    public AjaxResult selectoffer( @PathVariable Long id){
        log.debug("将报价单添加到数据库");
        QuotedPriceVo quotedPriceVo = opemSeroesService.SelectquotedPrice(id);
        return  success(quotedPriceVo);

    }


    /**
     * 通用上传请求（单个）
     */

    @Anonymous
    @PostMapping("/uploads")
    @ApiOperation("上传图片")
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        String bucketName=minioPojo.getBucketName();
        log.debug("bucketName",bucketName);
        try(InputStream inputStream = file.getInputStream()){
//判断桶是否存在
            boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!bucketExists){
//                如果不存在，就创建桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }
//            本地时间，具体到年、月、日
            String yyyymmdd = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            //防止名字重复
            String uuid= UUID.randomUUID().toString();
            String filename = yyyymmdd+"/"+uuid+file.getOriginalFilename();
//          加一个/表示创建一个文件夹
            minioClient.putObject(PutObjectArgs.builder().
                    bucket(bucketName).
                    object(filename).
                    stream(file.getInputStream(), file.getSize(), -1).
//                    文件上传的类型，如果不指定，那么每次访问时都要先下载文件
        contentType(file.getContentType()).
                            build());
            String url= minioPojo.getUrl()+"/"+minioPojo.getBucketName()+"/"+filename;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", "/"+minioPojo.getBucketName()+"/"+filename);
            ajax.put("newFileName", FileUtils.getName(filename));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        } catch (Exception e) {
            @Cleanup InputStream is =  file.getInputStream();
            throw new RuntimeException("文件上传失败", e);
        }
    }

    @Anonymous
    @DeleteMapping("/delete")
    @ApiOperation("删除图片")
    public AjaxResult deleteFile(@RequestParam String url) {
        try {
            // 提取文件路径
            String filePath = extractFilePathFromUrl(url);

            minioClient.removeObject(RemoveObjectArgs.builder()
                    .bucket(minioPojo.getBucketName())
                    .object(filePath)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(url + "文件删除失败");
        }
        return AjaxResult.success();
    }

    private String extractFilePathFromUrl(String url) {
        // 找到第三个斜杠的位置
        int firstSlashIndex = url.indexOf('/');
        int secondSlashIndex = url.indexOf('/', firstSlashIndex + 1);
        int thirdSlashIndex = url.indexOf('/', secondSlashIndex + 1);
        int threeIndex = url.indexOf('/', thirdSlashIndex + 1);
        if (threeIndex != -1) {
            // 从第三个斜杠的下一个字符开始截取
            return url.substring(threeIndex + 1);
        } else {
            // 如果没有找到第三个斜杠，返回空字符串或其他默认值
            return "";
        }
    }


    @Anonymous
    @PostMapping( "/addPDF")
    @ApiOperation("将报价单pdf添加到数据库")
    public AjaxResult addPDF( @RequestBody PricePdfDto pricePdfDto){
        log.debug("将报价单添加到数据库");
        Long aLong = opemSeroesService.insertPDF(pricePdfDto);
        if (aLong == null || aLong == 0 ||aLong.equals("")){
            return AjaxResult.error("添加失败");
        }
        return  success(aLong);

    }

    @Anonymous
    @GetMapping("/case/{id}")
    @ApiOperation("根据案件id查询资料")
    public AjaxResult getcaseInfo(@PathVariable Long id){
        log.debug("开始通过id查询案件资料的接口");
        CaseVo selectcasebyid = caseService.selectcasebyidAndContacts(id);
        return  success(selectcasebyid);
    }

    @Anonymous
    @GetMapping("/item/delete/{id}")
    @ApiOperation("通过id删除报价单数据")
    public AjaxResult deleteitem(@PathVariable("id")Long id){
        log.debug("开始通过id删除报价单数据");
        int i = opemSeroesService.deleteitem(id);
        if (i == 0){
            return AjaxResult.error("删除失败");
        }
        return  success(i);
    }





}
